from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as pyplot
import sklearn
from sklearn import linear_model
from sklearn.utils import shuffle
import pickle

examDcit = {'学习时间': [0, 5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3, 3.25, 3.5, 5, 4.25, 4.5, 4.75, 5, 5.5, 6],
            '学习成绩': [10, 22, 13, 43, 20, 22, 23, 33, 50, 62, 38, 55, 75, 62, 73, 81, 76, 64, 82, 90, 93]}
examOrderDic = OrderedDict(examDcit)
examDf = pd.DataFrame(examOrderDic)
# print(examDf.head())
exam_X = examDf.loc[:, '学习时间']
exam_Y = examDf.loc[:, '学习成绩']
# 把原始主数据按照20%分割  表示测试集包含原始数据的20%
x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(exam_X, exam_Y, test_size=0.2)
x_train = x_train.values.reshape(-1, 1)
y_train = y_train.values.reshape(-1, 1)
model = linear_model.LinearRegression()
model.fit(x_train, y_train)
with open("studenGrademodel.pickle", "wb") as f:
    pickle.dump(model, f)

pickle_in = open("studenGrademodel.pickle", "rb")
model = pickle.load(pickle_in)
# 线性回归模型的系数
print('Coefficient:\n', model.coef_)
# 线性回归模型的截距
print('Intercept:\n', model.intercept_)
pyplot.scatter(exam_X, exam_Y, color='red', label='学习成绩')
pyplot.scatter(x_train, y_train, color='blue', label='训练数据')
pyplot.scatter(x_test, x_test, color='green', label='测试数据')
y_train_pred = model.predict(x_train)
pyplot.plot(x_train, y_train_pred, color='green', linewidth=3, label='最佳拟合线')
pyplot.xlabel("studyTime")
pyplot.ylabel("study Grade")
pyplot.show()

rdf = examDf.corr()
print('相关系数矩阵： ', rdf)

x_test = x_test.values.reshape(-1, 1)
y_test = y_test.values.reshape(-1, 1)
score = model.score(x_test, y_test)
print('决定系数R平方:', score)
